package com.qing.administer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qing.administer.entity.SysRoleMenu;
import com.qing.administer.entity.SysRoleMenu;
import com.qing.administer.mapper.SysRoleMenuMapper;
import com.qing.administer.service.SysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author qing
 * @since 2021-09-17
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {


    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean editSysRoleMenu(Long roleId, List<Long> menuIds) {
        QueryWrapper<SysRoleMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<SysRoleMenu> existSysRoleMenuList=sysRoleMenuMapper.selectList(queryWrapper);

        //求集合交集--不需要改变的数据
        List<Long> commonRoleList= existSysRoleMenuList.stream().map(item->item.getRoleId())
                .filter(item->menuIds.contains(item))
                .collect(Collectors.toList());

        //数据库--与交集的差集需要删除的部分
        List<Long> removeIds=existSysRoleMenuList.stream().filter(item->!commonRoleList.contains(item.getRoleId())).map(item->item.getId()).collect(Collectors.toList());

        //传值--与交集的差集需要添加的部分
        menuIds.stream().filter(item->!commonRoleList.contains(item)) //取差集
                .map(menuId->new SysRoleMenu(roleId,menuId)).forEach(sysRoleMenu->{
            sysRoleMenuMapper.insert(sysRoleMenu);
        });
        if(CollectionUtils.isNotEmpty(removeIds)){
            sysRoleMenuMapper.deleteBatchIds(removeIds);
        }

        return  true;
    }

    @Override
    public List<Long> selectSysRoleMenuIdList(Long roleId) {
        QueryWrapper<SysRoleMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<SysRoleMenu> sysRoleMenuList=sysRoleMenuMapper.selectList(queryWrapper);
        return  sysRoleMenuList.stream().map(item->item.getRoleId()).collect(Collectors.toList());
    }
}
